#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, subprocess, re
from logger import Logger

def writeChapterFile(logger, baseName, chapterLen, movieLengthInSec):
    fileName = baseName+'_chapters.txt'
    outfile = open(fileName, "w")
    chapters = (movieLengthInSec/60)/chapterLen
    hours = 0
    minutes = 0
    chapterdata = ""

    for count in range(0,chapters+1):
        chapterdata = chapterdata + ('CHAPTER%.2d=%.2d:%.2d:00.000\n' % (count,hours,minutes))
        chapterdata = chapterdata + ('CHAPTER%.2dNAME=Chapter %.2d\n' % (count,count))
        minutes = minutes + chapterLen
        if minutes >= 60:
            minutes = 0
            hours = hours + 1

    outfile.write(chapterdata)
    outfile.flush()
    outfile.close()
    if logger:
        logger.log('echo "%s" > "%s"' % (chapterdata,fileName))
    return fileName

def getvideolengthinsec(vidfile):
    output = subprocess.Popen(['ffmpeg', '-i', vidfile], stderr = subprocess.PIPE).communicate()[1]
    videolen = re.compile('Duration: (\d{2}):(\d{2}):(\d{2})\.(\d{2}), .*? bitrate: .*?\n').search(output)
    if videolen:
        vLen = int(videolen.group(1))*60*60
        vLen = vLen + int(videolen.group(2))*60
        vLen = vLen + int(videolen.group(3))
        return vLen
    else:
        print 'Can not find video length!'    
    return None

def main():
    fname = sys.argv[1]
    clen = 5
    if len(sys.argv)>2:
        clen = int(sys.argv[2])
    videoLenInSec = getvideolengthinsec(fname)
    cfname = writeChapterFile(None, fname, clen, videoLenInSec)
    print 'Created chapter file: '+cfname

if __name__ == '__main__':
    main()
